﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TidyBlog.Data
{
    /// <summary>
    /// UDPATE操作命令生成类
    /// </summary>
    public class UpdateCommand : Command
    {
        /// <summary>
        /// 字段
        /// </summary>
        protected List<ColumnValuePair> UpdateColumns;


        public UpdateCommand(string table)
            : base(table)
        {

        }

        public UpdateCommand(string[] tables)
            : base(tables)
        {

        }


        /// <summary>
        /// 指定更新的列
        /// </summary>
        /// <param name="column">列</param>
        /// <returns>当前命令</returns>
        public UpdateCommand Set(ColumnValuePair column)
        {
            if (column != null)
            {
                UpdateColumns = new List<ColumnValuePair>();
                UpdateColumns.Add(column);
            }

            return this;
        }
        
        /// <summary>
        /// 指定更新的列
        /// </summary>
        /// <param name="columns">列</param>
        /// <returns>当前命令</returns>
        public UpdateCommand Set(IEnumerable<ColumnValuePair> columns)
        {
            UpdateColumns = new List<ColumnValuePair>(columns);

            return this;
        }

        /// <summary>
        /// 获取更新列字符串
        /// </summary>
        /// <returns>更新列字符串</returns>
        protected string GetColumnString()
        {
            var result = new StringBuilder();
            var paramPrefix = DbHelper.Provider.ParamPrefix;

            foreach (var column in UpdateColumns)
            {
                if (result.Length > 0)
                {
                    result.Append(",");
                }

                result.Append(column.Name);
                result.Append("=");
                if (column.IsParamValue)
                {
                    result.Append(paramPrefix);
                }
                result.Append(column.Value);
            }

            return result.ToString();
        }

        /// <summary>
        /// 生成SQL命令字符串
        /// </summary>
        /// <returns>SQL命令字符串</returns>
        public override string ToString()
        {
            return String.Format(DbHelper.Provider.GetCmdTemplate("UPDATE"),
                GetTableString(), GetColumnString(), GetWhereString());
        }
    }
}